
#include <util/common_macros.h>
#include <imp/image/image.h>

#include "camcal.h"
// =============================================================================

#define __proc proc

// =============================================================================


static gboolean __loop(CamCal * cc) {

	char * buff;
	buff = v4l_interface_grab_rgb(cc->v4li, cc->image_rgb->data);

	gtk_widget_queue_draw(GTK_WIDGET(cc->da_image));

	return TRUE;
}

static void __alloc_work_memory(CamCal * cc) {

	if (cc->image_rgb) imp_image_delete(cc->image_rgb);
	

	cc->image_rgb = imp_image_new(cc->v4li->v4ldrv.width, cc->v4li->v4ldrv.height, IMP_IMAGE_TYPE_RGB);
	

}

static void __event_v4li_start(v4lInterface * v4li, gpointer data) {

	CamCal * cc = (CamCal *) data;

	gtk_widget_set_size_request(GTK_WIDGET(cc->da_image), cc->v4li->v4ldrv.width, cc->v4li->v4ldrv.height);

	__alloc_work_memory(cc);

	//start loop
	cc->handle_loop = g_idle_add((GSourceFunc) __loop, cc);
}

static void __event_v4li_stop(v4lInterface * v4li, gpointer data) {

	CamCal * cc = (CamCal *) data;

	if (cc->handle_loop == -1) return;

	
	// stop loop
	g_source_remove(cc->handle_loop);
	cc->handle_loop = -1;
}

/* ========================================================================== */
static gboolean __event_expose_da_image(GtkWidget * drawarea, GdkEvent * e, gpointer data) {

	CamCal * cc;
	cc = (CamCal *) data;

	GtkWidget * widget = GTK_WIDGET(drawarea);
	GdkWindow * window = gtk_widget_get_window(GTK_WIDGET(widget));
	ImpImage * Img = NULL;

	// Select image
	Img = cc->image_rgb;

	if (Img == NULL) return FALSE;
	if (Img->data == NULL) return FALSE;

	gdk_draw_rgb_image(window, widget->style->fg_gc[GTK_STATE_NORMAL],
			0, 0, Img->width, Img->height,
			GDK_RGB_DITHER_MAX, Img->data, Img->stride);

	return FALSE;
}

/* ========================================================================== */
void __camcal_init_events(CamCal * cc) {

	int i;
	gtk_widget_set_size_request(GTK_WIDGET(cc->da_image), 320, 240);
	g_signal_connect(G_OBJECT(cc->da_image), "expose-event", G_CALLBACK(__event_expose_da_image), cc);

	g_signal_connect(G_OBJECT(cc->v4li), "v4li-start-event", G_CALLBACK(__event_v4li_start), cc);
	g_signal_connect(G_OBJECT(cc->v4li), "v4li-stop-event", G_CALLBACK(__event_v4li_stop), cc);


}
